#!/usr/bin/python
"""

This script is intended to automate the task of publishing and shareing photos in directories of your harddrive.

It links all files that start with a prefix (standard '1_') to a web server path (default /var/www/album) and runs the script album (http://marginalhacks.com/Hacks/album/) in the webserver path to create a Web Album of all the pictures in the whole directory tree. It will therefore create subalbums for every directory level.
It also autoratates all images based on their orientation exif information (if available).

To use it rename all files in your picture directory that you want to be web-published with the prefix and start the script (in a terminal) in the root of your picture directory. 

"""


import tkMessageBox
import os
import logging

WEBPATH = "/var/www/album"
PREFIX = "1_"
ALBUMARGS = "-sort date -medium 800 -theme Dominatrix6 -theme_path /var/www/Themes/ -theme_url /Themes"

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

def create_symlinks_for_prefix(source_root, new_root, prefix):
    """
    Creates recursivly symlinks into new root from files under source root,
    for files which names start with a prefix.
    Necessary directories are created under the new root.
    """
    log.debug("create_symlinks_for_prefix(source_root='%s', new_root='%s', prefix='%s'):"
              % (source_root, new_root, prefix))
    for fullpath, dirnames, filenames in os.walk(source_root):
        relpath = os.path.relpath(fullpath,source_root)
        for filename in filenames:
            if filename.startswith(prefix):
                newpath = os.path.join(new_root, relpath, filename)
                log.debug("processing '%s'" % newpath)
                if not os.path.exists(newpath):
                    try:
                        os.makedirs(os.path.join(new_root, relpath))
                    except OSError:
                        pass # already exists
                    os.symlink(os.path.join(fullpath, filename), newpath)
                    os.system("jhead -ft -autorot %s" % newpath)
                    log.info("link '%s' created." % newpath)
                    
def create_album(path, album_args):
    os.chdir(path)
    cmd ="album %s" % album_args
    log.debug("calling: '%s' in '%s'" % (cmd, path))
    os.system(cmd)

#tkMessageBox.askyesno("test %s" % os.getcwd())


def main():
    oldumask = os.umask(2)
    create_symlinks_for_prefix(os.getcwd(), WEBPATH, PREFIX)
    create_album(WEBPATH, ALBUMARGS)
    os.chdir(WEBPATH)
    os.system("chmod -R g+w *")
    os.umask(oldumask)
    
main()
# raw_input("Press any key to continue")
